import 'dart:io';

import 'package:baidu_map/utils/log_util.dart';
import 'package:flutter/material.dart';
import 'package:flutter_baidu_mapapi_map/flutter_baidu_mapapi_map.dart';
import 'package:flutter_bmflocation/flutter_bmflocation.dart';
import 'package:flutter_baidu_mapapi_base/flutter_baidu_mapapi_base.dart';

class SingleLocationPage extends StatefulWidget {
  const SingleLocationPage({Key? key}) : super(key: key);

  @override
  State<SingleLocationPage> createState() => _SingleLocationPageState();
}

class _SingleLocationPageState extends State<SingleLocationPage> {

  BaiduLocation _locationResult = BaiduLocation();
  late BMFMapController _myMapController;
  final LocationFlutterPlugin _myLocPlugin = LocationFlutterPlugin();
  bool _suc = false;



  @override
  void initState() {
    super.initState();
    if (Platform.isIOS) {
      _myLocPlugin.singleLocationCallback(callback: (BaiduLocation result) {
        setState(() {
          _locationResult = result;
          locationFinish();
        });
      });
    } else if (Platform.isAndroid) {
      _myLocPlugin.seriesLocationCallback(callback: (BaiduLocation result) {
        setState(() {
          _locationResult = result;
          locationFinish();
          _myLocPlugin.stopLocation();
        });
      });
    }
  }

  void locationFinish() {
    BMFMarker marker = BMFMarker.icon(
      position: BMFCoordinate(
        _locationResult.latitude ?? 0.0,
        _locationResult.longitude ?? 0.0
      ),
      title: 'flutterMarker',
      identifier: "flutter_marker",
      icon: 'resoures/icon_mark.png'
    );

    _myMapController.addMarker(marker);
    _myMapController.setCenterCoordinate(
      BMFCoordinate(
          _locationResult.latitude ?? 0.0,
          _locationResult.longitude ?? 0.0
      ),
      false
    );
  }

  @override
  Widget build(BuildContext context) {
    List<Widget> resultWidgets = [];

    if(_locationResult.locTime != null) {
      _locationResult.getMap().forEach((key, value) {
        resultWidgets.add(_resultWidget(key, value));
      });
    }

    return Scaffold(
      // appBar: BMFAppBar(
      //   title: '单次定位',
      //   isBack: true,
      //   onBack: () {
      //     Navigator.of(context).pop();
      //   },
      // ),
      appBar: AppBar(
        title: const Text('单次定位'),
      ),
      body: Stack(
        children: [
          Positioned(
            child: _createMapContainer(),
          ),
          Container(height: 20),
          SizedBox(
            height: MediaQuery.of(context).size.height - 500,
            child: ListView(
              children: resultWidgets,
            ),
          ),
          _createButtonContainer()
        ],
      ),
    );
  }

  Widget _createMapContainer() {
    return SizedBox(
      height: 300,
      child: BMFMapWidget(
        onBMFMapCreated: (controller) {
          onBMFMapCreated(controller);
        },
        mapOptions: initMapOptions(),
      ),
    );
  }

  Widget _createButtonContainer() {
    return Container(
      alignment: Alignment.bottomCenter,
      child: ElevatedButton(
        onPressed: () {
          _locationAction();
          _startLocation();
        },
        style: ButtonStyle(
          backgroundColor: MaterialStateProperty.all(Colors.blueAccent),
          overlayColor: MaterialStateProperty.all(Colors.yellow),
          shape: MaterialStateProperty.all(RoundedRectangleBorder(
            borderRadius: BorderRadius.circular(5)
          ))
        ),
        child: const Text('开始定位'),
      ),
    );
  }

  Widget _resultWidget(key,value) {
    return Center(
      child: Column(
        mainAxisAlignment: MainAxisAlignment.center,
        children: <Widget>[
          Text('$key:' ' $value')
        ],
      ),
    );
  }
  void _locationAction() async {
    Map iosMap = initIOSOptions().getMap();
    Map androidMap = initAndroidOptions().getMap();

    _suc = await _myLocPlugin.prepareLoc(androidMap, iosMap);

    LogUtil.i('设置定位参数iosMap: $iosMap');
    LogUtil.i('设置定位参数androidMap: $androidMap');
  }

  BaiduLocationAndroidOption initAndroidOptions() {
    return BaiduLocationAndroidOption(
      coorType: 'bd09ll',
      locationMode: BMFLocationMode.hightAccuracy,
      isNeedAddress: true,
      isNeedAltitude: true,
      isNeedLocationPoiList: true,
      isNeedNewVersionRgc: true,
      isNeedLocationDescribe: true,
      openGps: true,
      locationPurpose: BMFLocationPurpose.sport,
      coordType: BMFLocationCoordType.bd09ll
    );
  }

  BaiduLocationIOSOption initIOSOptions() {
    return BaiduLocationIOSOption(
      coordType: BMFLocationCoordType.bd09ll,
      BMKLocationCoordinateType: 'BMKLocationCoordinateTypeBMK09LL',
      desiredAccuracy: BMFDesiredAccuracy.best
    );
  }

  Future<void> _startLocation() async {
    if (Platform.isIOS) {
      _suc = await _myLocPlugin
        .singleLocation({
          'isReGeocode': true,
          'isNetworkState': true
        });
      LogUtil.i('开始单次定位: $_suc');
    } else if (Platform.isAndroid) {
      _suc = await _myLocPlugin.startLocation();
    }
  }

  BMFMapOptions initMapOptions() {
    return BMFMapOptions(
      center: BMFCoordinate(
        39.917215,
        116.380341
      ),
      zoomLevel: 12,
      mapPadding: BMFEdgeInsets(top: 0, left: 0, right: 0, bottom: 0)
    );
  }

  void onBMFMapCreated(BMFMapController controller) {
    _myMapController = controller;
    _myMapController.setMapDidLoadCallback(callback: () {
      LogUtil.i('mapDidLoad-地图加载完成');
    });
  }
}
